import React, { useState } from 'react';
import { Card, Form, Input, Button, Checkbox, Tooltip, Image, message } from 'antd';
import { useNavigate } from 'react-router-dom';

export default function Login() {
  const [type, setType] = useState(0); // 0: login, 1: forgot
  const [loading, setLoading] = useState(false);
  const [failNum, setFailNum] = useState(0);
  const navigate = useNavigate();

  const [form] = Form.useForm();
  const [forgotForm] = Form.useForm();

  const onLogin = async (values) => {
    setLoading(true);
    try {
      // 模拟登录失败次数累积（模仿 Vue 里 failNum > 2 显示验证码）
      if (!values.account || !values.password) {
        throw new Error('请输入账号和密码');
      }
      // TODO: 调用后端登录 API
      // 模仿 admin-web：登录成功后写入菜单列表与登录状态，并跳转首页
      const mockMenuList = [
        { name: 'Home', path: '/main' },
        { name: 'Machine Group', path: '/machine/group' },
        { name: 'Machine List', path: '/machine/list' },
      ];
      localStorage.setItem('menuList', JSON.stringify(mockMenuList));
      localStorage.setItem('isLoggedIn', 'true');

      message.success('登录成功');
      navigate('/main', { replace: true });
    } catch (e) {
      setFailNum((n) => n + 1);
      message.error(e.message || '登录失败');
    } finally {
      setLoading(false);
    }
  };

  const onForgot = async (values) => {
    setLoading(true);
    try {
      if (!values.emailManger || !values.captcha || !values.newPassword) {
        throw new Error('请完整填写找回信息');
      }
      // TODO: 调用后端找回密码 API
      message.success('密码更新成功（示例）');
      setType(0);
    } catch (e) {
      message.error(e.message || '更新失败');
    } finally {
      setLoading(false);
    }
  };

  const containerStyle = {
    width: '100%',
    height: '100%',
    minHeight: '100vh',
    background: '#f5f7fa',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  };

  const panelStyle = {
    width: 850,
    display: 'flex',
    borderRadius: 6,
    boxShadow: 'rgba(0,0,0,0.2) -1px -1px 25px',
    overflow: 'hidden',
    background: '#fff',
  };

  const leftStyle = {
    width: 470,
    padding: '24px 0 36px 36px',
    borderRight: '1px solid #ccc',
    backgroundColor: '#fff',
  };

  const rightStyle = {
    width: 350,
    backgroundColor: '#fff',
    padding: 24,
  };

  return (
    <div style={containerStyle}>
      <div style={panelStyle}>
        <div style={leftStyle}>
          <div style={{ fontSize: 32, color: '#00e1ad', fontWeight: 'bold', marginBottom: 0 }}>Vending Machine</div>
          <div style={{ color: '#321108', margin: '10px 0 4px' }}>
            Vending Machine software/backstage Self-service vending machine management through mobile device.
          </div>
          <div style={{ color: '#321108', margin: '4px 0 10px 0' }}>
            Click the link below to download the APP.
          </div>

          <div style={{ display: 'flex', alignItems: 'center', marginTop: 30, gap: 17 }}>
            <Tooltip title={<Image src="/vite.svg" width={150} />} placement="bottom">
              <div
                onClick={() => message.info('跳转 iOS 下载（示例）')}
                style={{ width: '44%', height: 48, backgroundColor: '#321108', cursor: 'pointer', borderRadius: 4, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
              >
                <div style={{ marginLeft: 5, fontWeight: 'bold', lineHeight: '18px', fontSize: 14 }}>
                  <div>iOS App</div>
                  <div style={{ fontWeight: 'normal' }}>Download</div>
                </div>
              </div>
            </Tooltip>
            <Tooltip title={<Image src="/vite.svg" width={150} />} placement="bottom">
              <div
                onClick={() => message.info('跳转 Android 下载（示例）')}
                style={{ width: '44%', height: 48, backgroundColor: '#321108', cursor: 'pointer', borderRadius: 4, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
              >
                <div style={{ marginLeft: 5, fontWeight: 'bold', lineHeight: '18px', fontSize: 14 }}>
                  <div>Android App</div>
                  <div style={{ fontWeight: 'normal' }}>Download</div>
                </div>
              </div>
            </Tooltip>
          </div>
        </div>

        <div style={rightStyle}>
          {type === 0 ? (
            <Card title="Login" variant="borderless">
              <Form form={form} layout="vertical" onFinish={onLogin}>
                <Form.Item name="account" rules={[{ required: true, message: '请输入账号' }]}> 
                  <Input placeholder="用户名 / 邮箱" />
                </Form.Item>
                <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}> 
                  <Input.Password placeholder="密码" />
                </Form.Item>
                {failNum > 2 && (
                  <div style={{ display: 'flex', gap: 8 }}>
                    <Form.Item name="code" style={{ flex: 1 }} rules={[{ required: true, message: '请输入验证码' }]}> 
                      <Input placeholder="验证码" />
                    </Form.Item>
                    <div style={{ width: 130, height: 34, border: '1px solid #dcdfe6', borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <span style={{ fontSize: 12, color: '#666' }}>点击刷新</span>
                    </div>
                  </div>
                )}

                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Checkbox>记住密码</Checkbox>
                  <Button type="link" onClick={() => setType(1)}>忘记密码</Button>
                </div>

                <Button type="primary" htmlType="submit" loading={loading} style={{ width: '100%', marginTop: 20 }}>
                  {loading ? '正在登录...' : '登录'}
                </Button>
              </Form>
            </Card>
          ) : (
            <Card title="Forgot Password" variant="borderless">
              <Form form={forgotForm} layout="vertical" onFinish={onForgot}>
                <Form.Item name="emailManger" rules={[{ required: true, message: '请输入管理员邮箱' }]}> 
                  <Input placeholder="管理员邮箱" />
                </Form.Item>
                <Form.Item name="captcha" rules={[{ required: true, message: '请输入验证码' }]}> 
                  <Input placeholder="验证码" />
                </Form.Item>
                <Form.Item name="newPassword" rules={[{ required: true, message: '请输入新密码' }]}> 
                  <Input.Password placeholder="新密码" />
                </Form.Item>
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <Button type="link" onClick={() => setType(0)}>返回登录</Button>
                </div>
                <Button type="primary" htmlType="submit" loading={loading} style={{ width: '100%', marginTop: 20 }}>
                  {loading ? '正在更新...' : '更新密码'}
                </Button>
              </Form>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}
